package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UtilisateurDAO;

/**
 * Servlet implementation class profilUser
 */
@WebServlet("/profilUser")
public class ProfilUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String VUE = "/WEB-INF/profilUser.jsp";
	public static final String VUE_INDEX = "/WEB-INF/connectionUser.jsp";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ProfilUser() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		/* Récupération de la session depuis la requête */
		HttpSession session = request.getSession();

		if (session.getAttribute("user") != null) {
			this.getServletContext().getRequestDispatcher(VUE)
					.forward(request, response);
		} else {
			this.getServletContext().getRequestDispatcher(VUE_INDEX)
					.forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String contextPath = request.getContextPath();

		// recuperation du cookie contenant la variable idUser
		Cookie[] lesCookies = request.getCookies();
		int idUser = Integer.parseInt(lesCookies[1].getValue());

		// on recupere les informations utilisateur
		String mail = request.getParameter("emailUser");
		String login = request.getParameter("loginUser");
		String mdp = request.getParameter("mdpUser");

		UtilisateurDAO userDAO = new UtilisateurDAO();
		userDAO.changeUser(idUser, mail, login, mdp);

		// on appelle l'autre servlet
		response.sendRedirect(response.encodeRedirectURL(contextPath
				+ "/profilUser"));
	}

}
